package com.jueling.culture.core.interceptor;


import com.jueling.culture.compent.RedisComponent;
import com.jueling.culture.core.service.TokenManageService;
import com.jueling.culture.exception.TokenErrResolveException;
import com.jueling.culture.exception.TokenResolveException;
import com.jueling.culture.model.UserInfo;
import com.jueling.culture.util.EncryptionUtil;
import com.jueling.culture.util.RedisKeyGeneratorUtil;
import com.jueling.culture.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author linp
 * @date  2019/6/12
 */
@Slf4j
@Component
public class LoginHandlerInterceptorAdapter extends HandlerInterceptorAdapter {
    private static final String AUTHORIZATION = "Authorization";

    public static final String ACC_SECRET_KEY = "fjgtLokiLhshOdin";

    @Autowired
    private RedisComponent redisComponent;
    @Autowired
    private TokenManageService tokenManageService;

    /**
     * token认证
     * @param request
     */
    public boolean validateSign(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //解决跨域问题
        if(request.getMethod().equals(HttpMethod.OPTIONS.name())){
            return true;
        }
        //验证签名
        boolean pass = validate(request);
        if (pass) {
            return true;
        }
        throw new TokenResolveException("登录状态已过期，请重新登录");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        validateSign(request,response);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理资源
        UserInfo.currentUser.remove();
    }

    /**
     * token认证
     */
    private boolean validate(HttpServletRequest request) {
        String token = request.getHeader(AUTHORIZATION);
        String decrypt = EncryptionUtil.aseDecrypt(token, ACC_SECRET_KEY);
        if (StringUtil.isEmptyStr(decrypt)) {
            return false;
        }
        String[] split = decrypt.split(":");
        UserInfo userInfo = redisComponent.getObj(RedisKeyGeneratorUtil.accessTokenRedisKeyGenerator(split[0]), UserInfo.class);
        if(userInfo == null){
            return false;
        }
        if (!userInfo.getRandom().equals(split[1])) {
            throw new TokenErrResolveException("该账号已在其他设备登录，请重新登录");
        }
        //验证成功，把用户放到当前用户下
        UserInfo.currentUser.set(userInfo);
        //刷新token时间
        tokenManageService.refreshToken(userInfo);
        return true;
    }

}
